<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8"/>
    <title>SourceTable</title>
    <link rel='stylesheet' href='./luckysheet/plugins/css/pluginsCss.css'/>
    <link rel='stylesheet' href='./luckysheet/plugins/plugins.css'/>
    <link rel='stylesheet' href='./luckysheet/css/luckysheet.css'/>
    <link rel='stylesheet' href='./luckysheet/assets/iconfont/iconfont.css'/>

    <script src="./luckysheet/js/plugin.js"></script>
    <script src="./luckysheet/js/luckysheet.umd.js"></script>
    <script src="./luckysheet/js/axios-0.18.0.js"></script>
    <script src="./luckysheet/js/vue.js"></script>

    <!-- 引入样式 -->
    <link rel="stylesheet" href="./luckysheet/css/index.css">
    <!-- 引入组件库 -->
    <script src="./luckysheet/js/index.js"></script>
    <script src="./luckysheet/js/url.js"></script>

</head>

<body>
<div id="app">
    <el-button type="info" style="float: right" size="small" @click="call" round>返回</el-button>
    <el-button type="primary" style="float: right;margin-right: 10px" size="small" @click="save" round>保存</el-button>
    <div style="margin:0px;padding:0px;position:absolute;width:20%;left: 43%;top: 48%;bottom: 0px;outline: none;">
        数据较大,正在渲染,请稍等。。。。。
    </div>
    <div id="luckysheet"
         style="margin:0px;padding:0px;position:absolute;width:100%;left: 0px;top: 50px;bottom: 0px;outline: none;"></div>
</div>

<script>
    var vue = new Vue({
        el: '#app',
        data: {
            options: {
                container: 'luckysheet',
                title: 'Luckysheet Demo',
                lang: 'zh', // 设定表格语言
                row: 36, //行数
                column: 18, //列数
                // 是否显示工具栏
                showtoolbar: false,
                // 是否显示顶部信息栏
                showinfobar: false,
                // 是否显示sheet页签
                showsheetbar: false,
                // 是否显示公式栏
                sheetFormulaBar: false,
                // 是否允许新增行
                enableAddRow: false,
                hook: {
                    cellUpdated: "",
                    cellUpdateBefore: ""
                },
                data: [{
                    // sheet名
                    name: "sheet1",
                    defaultColWidth: 100, //自定义列宽
                    config: {
                        // 单元格合并配置
                        "merge": {},
                        // 单元格边框配置
                        "borderInfo": [{
                            "rangeType": "range",
                            "borderType": "border-all",
                            "style": "1",
                            "color": "#000000",
                            "range": [{
                                "row": [7, 8],
                                "column": [2, 3]
                            }]
                        }],
                        "authority": { //表单权限配置
                            "sheet": true, //保护该sheet
                            "hintText": "表头无法修改", //
                            "allowRangeList": [{ //区域保护
                                "name": "name", //名称
                                "password": "1", //密码
                                "hintText": "", //提示文字
                                "algorithmName": "None", //加密方案：MD2,MD4,MD5,RIPEMD-128,RIPEMD-160,SHA-1,SHA-256,SHA-384,SHA-512,WHIRLPOOL
                                "saltValue": null, //密码解密的盐参数，为一个自己定的随机数值
                                "sqref": "" //区域范围
                            }],
                        }
                    },
                    // 单元格数据配置
                    celldata: [],
                    // 行列冻结配置
                    frozen: {
                        type: 'rangeBoth',
                        range: {
                            row_focus: 0,
                            column_focus: 0
                        }
                    },
                }],

            },
            getBackend: "",
            //已修改行号
            row_number_list: new Set(),
            // id数据列表
            id_list: [],
            row_header_num: 0,
            col_header_num: 0,
            table_row_num: "",
            table_col_num: "",
            oid: 410,
            token: {
                headers: {
                    'Authorization': "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicmVzMSJdLCJ1c2VyX25hbWUiOiJrdWlodWEwMDEiLCJzY29wZSI6WyJhbGwiXSwiZXhwIjoxNjM3MDYzMDYyLCJhdXRob3JpdGllcyI6WyJSLWhlYWRPZmZpY2UiLCJraDAwMSJdLCJqdGkiOiJkOGEwOWNiOC1hZTVhLTQ1YjctYWY2MS1mZWYyYjQyZWM0YmEiLCJjbGllbnRfaWQiOiJjMSJ9.UN3ZWK6cb3GYGVWRaurVIpuxkX1K52SWIo93CIUndqM"
                }
            },
            backendUrl: "http://127.0.0.1:18082",
        },
        created() {
            this.backendUrl = window.backendUrl
            Request = this.GetRequest()

            this.token = {
                headers: {
                    'Authorization': Request.token
                }
            }

            this.oid = Request.oid;
        },
        mounted: function () {

            // 事件绑定
            this.options.hook.cellUpdateBefore = this.cellUpdated

            this.findSourceBody();

        },
        methods: {

            //参数初始化
            optionsS() {
                this.options = {
                    container: 'luckysheet',
                    title: 'Luckysheet Demo',
                    lang: 'zh', // 设定表格语言
                    row: 36, //行数
                    column: 18, //列数
                    // 是否显示工具栏
                    showtoolbar: false,
                    // 是否显示顶部信息栏
                    showinfobar: false,
                    // 是否显示sheet页签
                    showsheetbar: false,
                    // 是否显示公式栏
                    sheetFormulaBar: false,
                    // 是否允许新增行
                    enableAddRow: false,
                    hook: {
                        cellUpdated: "",
                        cellUpdateBefore: ""
                    },
                    data: [{
                        // sheet名
                        name: "sheet1",
                        defaultColWidth: 100, //自定义列宽
                        config: {
                            // 单元格合并配置
                            "merge": {},
                            // 单元格边框配置
                            "borderInfo": [{
                                "rangeType": "range",
                                "borderType": "border-all",
                                "style": "1",
                                "color": "#000000",
                                "range": [{
                                    "row": [7, 8],
                                    "column": [2, 3]
                                }]
                            }],
                            "authority": { //表单权限配置
                                "sheet": true, //保护该sheet
                                "hintText": "表头无法修改", //
                                "allowRangeList": [{ //区域保护
                                    "name": "name", //名称
                                    "password": "1", //密码
                                    "hintText": "", //提示文字
                                    "algorithmName": "None", //加密方案：MD2,MD4,MD5,RIPEMD-128,RIPEMD-160,SHA-1,SHA-256,SHA-384,SHA-512,WHIRLPOOL
                                    "saltValue": null, //密码解密的盐参数，为一个自己定的随机数值
                                    "sqref": "" //区域范围
                                }],
                            }
                        },
                        // 单元格数据配置
                        celldata: [],
                        // 行列冻结配置
                        frozen: {
                            type: 'rangeBoth',
                            range: {
                                row_focus: 0,
                                column_focus: 0
                            }
                        },
                    }],
                }
            },

            GetRequest() {
                var url = location.search; //获取url中"?"符后的字串

                var theRequest = new Object();
                if (url.indexOf("?") != -1) {
                    var str = url.substr(1);
                    strs = str.split("&");
                    for (var i = 0; i < strs.length; i++) {
                        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                    }
                }
                return theRequest;
            },
            // 获取表内数据
            getAll() {
                var list = luckysheet.getluckysheetfile()[0].data
                console.log(list)
            },
            // 查询源数据
            findSourceBody() {

                var that = this;

                axios.get(this.backendUrl + "/original/findByPid/" + this.oid, this.token).then((res) => {
                    axios.get(this.backendUrl + "/original/findRC/" + this.oid, this.token).then((res1) => {

                        this.optionsS()

                        that.row_header_num = res1.data.data.rowNum
                        that.col_header_num = res1.data.data.columnNum

                        row_header_num = res1.data.data.rowNum
                        col_header_num = res1.data.data.columnNum

                        let sourceList = []

                        //取出做大列
                        var row_num = 0

                        res.data.data.forEach(element => {
                            var item = eval('(' + element.data + ')')
                            if (row_num < item.length) {
                                row_num = item.length
                            }
                            sourceList.push(item)
                            this.id_list.push(element.id)
                        });

                        // 设置表格大小
                        this.options.column = row_num;
                        this.options.row = sourceList.length;

                        var w = this.createCellPos(row_num - 1)
                        var h = this.createCellPos(col_header_num)
                        let sqref = "$" + h + "$" + (row_header_num + 1) + ":$" + w + "$" + sourceList.length

                        // 设置可修改的表格范围
                        this.options.data[0].config["authority"]["allowRangeList"][0]["sqref"] = sqref

                        // 设置边框范围
                        this.options.data[0].config["borderInfo"][0]["range"][0]["row"] = [0, sourceList.length - 1]
                        this.options.data[0].config["borderInfo"][0]["range"][0]["column"] = [0, sourceList[0].length - 1]
                        // 处理表头
                        this.dispose_header(sourceList.slice(0, row_header_num))

                        // 固定行表头和列表头
                        this.options.data[0].frozen.range.row_focus = row_header_num - 1;
                        if (col_header_num > 0) {
                            this.options.data[0].frozen.range.column_focus = col_header_num - 1;
                        }

                        this.sourceList = sourceList

                        that.data_add(sourceList)

                    }).catch((err) => {
                        console.log(err);
                    });
                }).catch((err) => {
                    console.log(err);
                });
            },

            // 实体数据添加
            data_add(){
                sourceList = this.sourceList
                for (var i = 0; (i < sourceList.length && i < 16000); i++) {
                    for (var j = 0; j < sourceList[i].length; j++) {
                        bg = ""
                        if (i < row_header_num) {
                            bg = "#f6b26b";
                            ht = 0;
                        } else {
                            bg = "#ffffff";
                            ht = 1;
                            if (j >= col_header_num) {
                                ht = 2;
                            }
                        }

                        this.options.data[0].celldata.push({
                            "r": i,
                            "c": j,
                            "v": {
                                "v": sourceList[i][j],
                                "m": sourceList[i][j],
                                "bg": bg,
                                "vt": 0,
                                "ht": ht
                            },
                        })
                    }
                }

                luckysheet.create(this.options);
            },

            // 表头处理
            dispose_header(headers) {
                merge_list = []
                // 遍历表头行
                for (let row = 0; row < headers.length; row++) {
                    // 遍历表头行
                    for (let col = 0; col < headers[row].length; col++) {

                        // 判断该单元格是否被合并过
                        if (row > 0 && (headers[row][col] == "" || headers[row][col] == headers[row - 1][col])) {
                            break
                        }


                        // 遍历查询横向合并多少单元格
                        let merge_col_index = 1
                        for (merge_col_index; merge_col_index < headers[row].length - col; merge_col_index++) {
                            if (headers[row][col + merge_col_index] != headers[row][col] && headers[row][col + merge_col_index] != "") {
                                merge_col_index = merge_col_index;
                                break
                            }
                        }

                        // 遍历查询纵向合并多少单元格
                        let merge_row_index = 1
                        for (merge_row_index; merge_row_index < headers.length - row; merge_row_index++) {
                            if (headers[row + merge_row_index][col] != headers[row][col] && headers[row + merge_row_index][col] != "") {
                                merge_row_index = merge_row_index;
                                break
                            }
                        }

                        let key = row + "_" + col;
                        let value = {
                            "r": row,
                            "c": col,
                            "rs": merge_row_index,
                            "cs": merge_col_index
                        }

                        this.options.data[0].config["merge"][key] = value;

                        merge_list.push({
                            row: row,
                            col: col,
                            merge_row_index: merge_row_index,
                            merge_col_index: merge_col_index
                        })

                        if (merge_col_index > 0) {
                            col = col + merge_col_index - 1;
                        }
                    }
                }

                return merge_list;
            },
            createCellPos(n) {

                var ordA = 'A'.charCodeAt(0); //字母转unicode

                var ordZ = 'Z'.charCodeAt(0);

                var len = ordZ - ordA + 1;// 计算字母长度

                var s = "";

                while (n >= 0) {

                    s = String.fromCharCode(n % len + ordA) + s; // 将输入数字转换成字母

                    n = Math.floor(n / len) - 1; // 每次进行完需要重新floor向下取整，  -1是因为 A的unicode是0

                }

                return s;

            },

            //    单元格修改事件
            cellUpdated(r, c, value, isRefresh) {
                // 当前单元格类型 借方  调整数  报表数
                type = luckysheet.getCellValue(this.row_header_num - 1, c)
                if (value == null || value == "") {
                    value = 0;
                }

                // 如果是调整数或借贷数，则更新报表数
                let bb = 0;
                if (type == "借方" || type == "贷方") {
                    if (luckysheet.getCellValue(r, c + 1) != "" && luckysheet.getCellValue(r, c + 1) != null) {
                        bb = parseFloat(luckysheet.getCellValue(r, c + 1))
                    }
                    luckysheet.setCellValue(r, c + 2, bb + parseFloat(value))
                } else if (type == "调整数") {
                    if (luckysheet.getCellValue(r, c - 1) != "" && luckysheet.getCellValue(r, c - 1) != null) {
                        bb = parseFloat(luckysheet.getCellValue(r, c - 1))
                    }
                    luckysheet.setCellValue(r, c + 1, bb + parseFloat(value))
                }

                //    向行号变更数组添加行号
                this.row_number_list.add(r)
            },

            //    保存变更后数据
            save() {

                // 查询待修改数据的id
                let last_data_list = []
                this.row_number_list.forEach(row_number => {
                    let row_data = []
                    for (let i = 0; i < this.options.column; i++) {
                        row_data.push(luckysheet.getCellValue(row_number, i))
                    }
                    last_data_list.push({
                        "id": this.id_list[row_number],
                        "data": JSON.stringify(row_data)
                    })
                })

                axios.put(this.backendUrl + "/original", last_data_list, this.token).then((res) => {
                    this.$message({
                        message: res.data.message,
                        type: res.data.flag ? "success" : "error"
                    });
                }).catch((err) => {
                    console.log(err);
                });
            },

            call() {
                window.open("call=binding.original_data_page.bind=back")
            }

        }
    })
</script>
</body>

</html>